local skynet   = require "skynet"
local json     = require "cjson.safe"
local ws_agent = require "bw.server.ws_agent"
local protobuf = require "bw.protobuf"
local log      = require "bw.log"
local env      = require "env"

local id2proto = {}
local proto2id = {}

skynet.init(function()
    local file = io.open("./lualib/def/proto/define.json", "r")
    local str = file:read("a")
    local define = json.decode(str)
    for proto, id in pairs(define) do
        id2proto[id] = proto
        proto2id[proto] = id
    end

    protobuf.register_file("./lualib/def/proto/package.pb")
end)

local process = {
    test = require "process.test",
}

local function unpack(buff)
    local session, proto_id, msg = string.unpack(">I4>I4>s4", buff)
    local name = id2proto[proto_id]
    local data = protobuf.decode(name, msg)
    return {
        name    = name,
        session = session,
        data    = data,
    }
end

local function pack(req)
    local session = req.session
    local name = req.name
    local data = req.data
    local proto_id = proto2id[name]
    local msg = protobuf.encode(name, data)
    return string.pack(">I4>I4>s4", session, proto_id, msg)
end

ws_agent.start({
    protocol  = "ws",
    process   = process,
    unpack    = unpack,
    pack      = pack,
    is_binary = true,
})
